package com.fyt.service.Impl.user.account;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyt.controller.utils.Code;
import com.fyt.controller.utils.Result;
import com.fyt.entity.User;
import com.fyt.mapper.UserMapper;
import com.fyt.service.Impl.utils.UserDetailsImpl;
import com.fyt.service.user.account.LoginService;
import com.fyt.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper,User> implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result getToken(String account, String password) {
        //UsernamePasswordAuthenticationToken对象，包含用户的账号和密码，表示用户名密码认证方式。
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(account,password);
        //调用Security的authenticationManager接口对用户身份验证，
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //获取用户信息
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();
        String password1 = user.getPassword();
        //通过jwt工具类生成存有userid的token
        String jwt = JwtUtil.createJWT(user.getId().toString());
        System.out.println(jwt);
//        redisTemplate.opsForValue().set(user.getId(),jwt);
        return new Result(jwt,Code.get_ok,"登陆成功");
    }
}
